class TPeer {
    constructor(){
        this.code = null ;
        this.clientId = null ;
        this.sessionId = null ;
        this.endId = "";
    }
} 

class TKmsClient{
    constructor(){
        this.config={
            host:"gmggf8g.mqtt.iot.bj.baidubce.com",
            port:443,
            uid:"gmggf8g/peer",
            pwd:"a52bwKg22dCAuQzB",
            topics:{
                appTopic : "/hhmsg/notify",
                kmsCenterTopic : "/hhmsg/kmsCenter",
                clientTopic :"" 
            }
        };
        this.kmsConfig={
            kmsPeerOptions :{
                configuration: {
                    "iceServers": [ 
                        {
                            urls: "stun:223.68.161.139:3478"
                            //urls: "stun:223.112.194.253:40016"
                        },
                        {
                            urls: ["turn:223.68.161.139:3478"  ],
                            //urls: ["turn:223.112.194.253:40016"  ],
                            username: "kurento",
                            credential: "kurento"
                        }
                    ]
                },
                mediaConstraints: {
                    audio: true,
                    //video: {width: {exact: 1280}, height: {exact: 720}},
                    video: {
                        width: { min: 1280, ideal: 1280, max: 1920 },
                        height: { min: 720, ideal: 720 , max: 1080}
                    }
                }
            },
            kmsPeerTypes : {
                s: kurentoUtils.WebRtcPeer.WebRtcPeerSendonly,
                r: kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly,
                sr: kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv
            }
        }
        this.clientId = ['hhp',( new Date()).getTime() , parseInt(1000*Math.random())].join('');
        this.mqClient = "";  
        this.peers ={};
        this.candidateBuf ={};
    }
    open(){
        var me = this;
        return new Promise((success, faild)=>{
            try{
                var onConnect = function(){
                    
                }
                var onDisConnect = function(){
                    
                }
                var onRec = function(msg){
                    try{
                        if( msg.msgId =="candidate"){
                            var endId = msg.msgBody.endId;
                            if( me.peers[msg.msgBody.endId]){
                                var peer = me.peers[msg.msgBody.endId].peer;
                                peer.addIceCandidate(msg.msgBody.candidate);
                                console.log( msg);
                            }
                            else{
                                if(!me.candidateBuf[endId] ){
                                    me.candidateBuf[endId]=[];
                                }
                                me.candidateBuf[endId].push(msg.msgBody.candidate)
                            }
                        }
                    }
                    catch(eer){
                        console.log(eer);
                    }
                }
                commClient.openMqPro( me.clientId, onConnect , onDisConnect , onRec).then(mqClient=>{
                    me.mqClient = mqClient;
                    success(mqClient);
                })
            }
            catch(eer){
                console.log(eer);
                success();
            }
        })
    }
    createPeer( code , peerType , lv , rv ){
        var me = this;
        return new Promise((success, faild)=>{
            try{
                //var topic = commClient.config.mq.topics.appTopic+"/" + commClient.config.appId;
                var topic = 'hh/'+ commClient.config.appId+"/svr";
                var msgBody ={
                    code: code ,
                    clientId : me.clientId
                }
                var resPeer = new TPeer();
                resPeer.code = code ;
                resPeer.clientId = me.clientId;
                me.mqClient.sendMsgSync( topic , "reqSession" , msgBody).then(res=>{
                    console.log('client state:', me.mqClient.isConnected());
                    resPeer.sessionId = res.msgBody.sessionId;
                    // create peer 
                    var opts = JSON.parse(JSON.stringify(me.kmsConfig.kmsPeerOptions));
                    var creator = me.kmsConfig.kmsPeerTypes[peerType];
                    if( peerType=='s' ){
                        opts.localVideo = lv ;
                    }
                    else if( peerType=='r' ){
                        opts.remoteVideo = rv ;
                    }
                    else if( peerType=='sr' ){
                        opts.localVideo = lv ;
                        opts.remoteVideo = rv ;
                    }
                    resPeer.peer = creator(opts , function(erPeer){
                        resPeer.peer.on('icecandidate', function (candidate) {
                            var iceCandidate = kurentoClient.register.complexTypes.IceCandidate(candidate);
                            //endpoint.addIceCandidate(iceCandidate); 
                            console.log('candidate p->w')
                            var candaditeMsg ={
                                sessionId: resPeer.sessionId ,
                                cnadadite : iceCandidate
                            }
                            me.mqClient.sendMsg ( topic , "peCandidate" , candaditeMsg);
                        });

                        //sdp offer
                        resPeer.peer.generateOffer(function (errorPeerGenerateOffer, sdpOffer) {
                            var offMsgBody ={
                                sessionId: resPeer.sessionId ,
                                sdpOffer : sdpOffer,
                                code: code 
                            }
                            me.mqClient.sendMsgSync( topic , "sdpOffer" , offMsgBody , 50000).then(resSdp=>{
                                var answer = resSdp.msgBody.sdpAnswer;
                                var endId = resSdp.msgBody.endId;
                                resPeer.peer.processAnswer(answer, function(erAnswer){
                                    resPeer.endId = endId;
                                    me.peers[endId] = resPeer;
                                    if( me.candidateBuf[endId] && me.candidateBuf[endId].length>0 ){
                                        while(me.candidateBuf[endId].length>0){
                                            var candidate = me.candidateBuf[endId].shift();
                                            resPeer.peer.addIceCandidate(candidate);
                                        }
                                    }
                                    success(resPeer);   
                                })
                            })
                        });
                    })
                })
            }
            catch(eer){
                console.log(eer);
                success();
            }
        })
    } 
    connectMedia( srcId  , targetId , mediaType ){
        var me = this;
        try{ 
            var topic = 'hh/'+ commClient.config.appId+"/svr";
            var msgBody ={
                srcId: srcId ,
                targetId  : targetId ,
                mediaType : mediaType
            }
            me.mqClient.sendMsg ( topic , "connectMedia" , msgBody); 
        }
        catch(eer){
            console.log(eer);
            success();
        }
    } 
    loadPlayer( code  , url ){
        var me = this;
        return new Promise( (success,faild)=>{
            try{ 
                var topic = 'hh/'+ commClient.config.appId+"/svr";
                var msgBody ={
                    code: code ,
                    url : url
                }
                me.mqClient.sendMsgSync( topic , "loadPlayer" , msgBody).then(res=>{
                    console.log(res);
                    success(res);
                });
    
            }
            catch(eer){
                console.log(eer);
                success();
            }
        } )
    } 
}
